package service

import (
	"awesomeProject2/global"
	"awesomeProject2/model"
	"awesomeProject2/model/request"
	"awesomeProject2/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"strings"
)

func FillPaper(c *gin.Context, paper *model.Paper, requestInfo *request.Paper) {
	utils.StructAssign(paper, requestInfo)
	userid, _ := c.Get("userid")
	paper.UserId = userid.(uint)
	paper.PaperName = strings.TrimSpace(paper.PaperName)
	// 将request中的list数据转换成paper中的str
	paper.PaperFile = strings.Join(requestInfo.PaperFileList, ",")
	paper.PaperLevels = strings.Join(requestInfo.PaperLevelList, ",")
	paper.PaperRole = strings.Join(requestInfo.PaperRoleList, ",")
}

func CreatePaper(paper *model.Paper) (err error) {
	var paperInDB model.Paper

	err = global.GVA_DB.Where("paper_name = ?", paper.PaperName).First(&paperInDB).Error
	isNotFound := errors.Is(err, gorm.ErrRecordNotFound)
	// 不存在同名paper 直接保存到数据库
	if isNotFound {
		err = model.CreatePaper(paper)
		return err
	}
	// 存在同名的paper，需要进行特殊处理
	return someNamePaperProc(paper, &paperInDB, err)

}

func someNamePaperProc(paper *model.Paper, paperInDB *model.Paper, err error) error {
	if strings.Contains(paperInDB.PaperRole, ",") {
		return utils.BusinessError{
			Code: utils.ERROR_SOME_PAPER_NAME,
		}
	}

	if paperInDB.PaperRole == "一作" {
		paper.InvalidFlag = 1
	} else {
		paperInDB.InvalidFlag = 1
		// 更新数据库中同名Paper的计分标识字段
		if err := global.GVA_DB.Save(&paperInDB).Error; err != nil {
			return err
		}
	}

	err = model.CreatePaper(paper)
	return err
}

func GetPapersDynamic(info request.PaperSearchInfo) (err error, list interface{}, total int64) {
	var papers []model.Paper
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.Paper{})

	if info.PaperAuthors != "" {
		db = db.Where("paper_authors LIKE ?", "%"+info.PaperAuthors+"%")
	}
	if info.PaperName != "" {
		db = db.Where("paper_name LIKE ?", "%"+info.PaperName+"%")
	}

	if info.Level != "" {
		ids, err := model.GetPaperIdsByLevelId(info.Level)
		if err == nil {
			db = db.Where("id in ?", ids)
		}
	}

	if info.Category != "" {
		db = db.Where("paper_category = ?", info.Category)
	}
	if info.Year != "" {
		year, _ := strconv.Atoi(info.Year)
		db = db.Where("year = ?", year)
	}
	err = db.Count(&total).Error
	if err != nil {
		return err, nil, 0
	}
	err = db.Limit(limit).Offset(offset).Find(&papers).Error
	return err, papers, total
}
